const express = require("express")
router = express.Router()
const config = require("../config/config")
const async = require("async")
const axios = require("axios")
const User = require("../mongodb/user")
const multer = require("multer")
const upload = multer({ dest: 'public/avatar' });
const path = require("path")
const fs = require("fs")
//设置一些状态
let result = { status: 200, data: null, state: "成功" }
//登录api
router.post("/wx_login", async (req, res) => {
    try {

        let { code } = req.body
        console.log(code)
        let wx_loginUrl = "https://api.weixin.qq.com/sns/jscode2session"
        let data = {
            js_code: code,
            appid: config.applet.AppID,
            secret: config.applet.AppSecret,
            grant_type: "authorization_code"
        }
        const params = new URLSearchParams(data);
        const url = `${wx_loginUrl}?${params.toString()}`;
        let response = await axios.get(url)
    
        let result1 = response.data
        console.log(result1)
        let openid = result1.openid
        //去数据库查询有无该openid
        let user = await User.findOne({ openid })
        if (user) {
            // 查询到了匹配结果
            result.code = 200
            result.data = user
            result.state = "登录成功"
            result.isRegister = true
            console.log(result)
            res.send(result)
            return
        } else {
            // 未找到匹配结果
            result.code = 200
            result.data = user
            result.openid = openid
            result.isRegister = false
            result.state = "用户未注册 请先调用注册api"
            console.log(result)
            res.send(result)
            return
        }

    } catch {
        console.log(err)
        result.status = 500
        result.state = "失败"
        res.status = 500
        res.state = "服务器错误"
        res.send(result)
    }
})

//微信注册
router.post("/wx_register", async (req, res) => {
    try {
        let { openid, avatar, name } = req.body
        let file = req.file
        console.log(file)
        if(openid&&avatar&&name){
            let userdata = await User.findOne({openid})
            if(userdata){
                result.data = userdata
                result.code = 200
                result.state = "登录成功"
                result.isRegister = true
                console.log(result)
                res.send(result)
                return
            }
            let data = {
                openid,avatar,name,intr:"",staus:null,zflistId:[],
            }
            let user = await User.insertMany([data]);
            console.log(user)
            result.data = user[0]
            result.code = 200
            result.state = "登录成功"
            result.isRegister = true
            console.log(result)
            res.send(result)
            return

        }else{

            result.state = "失败"
            res.state = "请携带openid,avatar,name调用该接口"
            res.send(result)
            return
        }

    } catch (err) {
        console.log(err)
        result.status = 500
        result.state = "失败"
        res.status = 500
        res.state = "服务器错误"
        res.send(result)
    }
})

//头像上传
router.post("/avatar/upload",upload.any(), (req, res) => {
    console.log(req.files[0])
    if (!req.files[0]) {
        res.status(400).send('No file uploaded.');
        return;
      }
    console.log(req.files)
      // 在这里处理文件，如保存到指定目录、数据库等
      //获得名字
      let oldname = req.files[0].path
      //给新名字加上后缀
      let newname = req.files[0].path + path.parse(req.files[0].originalname).ext
      //重命名
      fs.renameSync(oldname,newname)
      let staticUrl = newname.replace('public', '');
      console.log(config.host.url+'/' + newname)
      res.json({
        err:0,
        url:config.host.url + staticUrl
      })

})
module.exports = router